package com.example.todolist.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;

import com.example.todolist.dto.sys.WxAuthLoginOrRegisterDTO;
import com.example.todolist.model.SysConfig;
import com.example.todolist.model.SysUser;
import com.example.todolist.response.BaseResponse;
import com.example.todolist.response.SystemResponse;
import com.example.todolist.service.SysConfigService;
import com.example.todolist.service.SysUserService;
import com.example.todolist.util.JwtUtil;
import com.example.todolist.util.WeChatCode2SessionReq;
import com.example.todolist.util.WeChatCode2SessionResp;
import com.example.todolist.util.WeChatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: yoonada
 * @email: m15602498163@163.com
 * @create: 2021-12-06 18:47
 * @description: 微信小程序业务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WxServiceImpl {

    private final SysConfigService sysConfigService;

    private final SysUserService sysUserService;

    private final JwtUtil jwtUtil;


    /**
     * 微信认证登录/注册
     *
     * @param wxAuthLoginOrRegisterDTO
     * @return
     */
    public BaseResponse wxAuthLoginOrRegister(WxAuthLoginOrRegisterDTO wxAuthLoginOrRegisterDTO) {
        String openId;
        openId = wxAuthLoginOrRegisterDTO.getWxOpenId();
        if (Objects.nonNull(openId)) {
            SysUser sysUser = sysUserService.selectByOpenId(openId);
            if (Objects.nonNull(sysUser)) {
                // 这里登录的账号密码皆为openId
                return SystemResponse.success(getToken(sysUser));
            }
        }
        SysUser newUser = SysUser
                .builder()
                .avatar(wxAuthLoginOrRegisterDTO.getAvatar())
                .nickname(wxAuthLoginOrRegisterDTO.getNickName())
                .wxOpenId(openId)
                .uid(IdUtil.simpleUUID())
                .build();
        sysUserService.save(newUser);
        return SystemResponse.success(getToken(newUser));
    }

    /**
     * 获取wx的openId
     * @param code
     * @return
     */
    public BaseResponse getWxOpenId(String code) {
        String wxOpenId = wxOpenId(code);
        return StringUtils.isBlank(wxOpenId)?BaseResponse.isFailed("获取openId时发生异常"):SystemResponse.success(wxOpenId);
    }

    /**
     * 获取openId
     * @param code
     * @return
     */
    public String wxOpenId(String code){
        SysConfig sysConfig = sysConfigService.list().get(0);
        WeChatCode2SessionReq req = WeChatCode2SessionReq
                .builder()
                .appKey(sysConfig.getWeChatAppId())
                .secret(sysConfig.getWeChatSecret())
                .code(code)
                .requestUrl(sysConfig.getWeChatAuthDomain())
                .build();
        String resp = WeChatUtil.code2Session(req);
        WeChatCode2SessionResp code2SessionResp = JSON.parseObject(resp, WeChatCode2SessionResp.class);
        return code2SessionResp.getOpenid();
    }

    /**
     * 生成用户的token
     * @param user
     * @return
     */
    private String getToken(SysUser user) {
        Map<String,Object> userMap = new HashMap<>(3);
        userMap.put("uid",user.getUid());
        userMap.put("open_id",user.getWxOpenId());
        userMap.put("nick_name",user.getNickname());
        return jwtUtil.generateToken(userMap);
    }
}